package com.yxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.common.PageResult;
import com.yxy.constant.MessageConstant;
import com.yxy.context.BaseContext;
import com.yxy.exception.NewsTitleAlreadyExistsException;
import com.yxy.mapper.NewsMapper;
import com.yxy.pojo.dto.NewsDTO;
import com.yxy.pojo.dto.NewsPageQueryDTO;
import com.yxy.pojo.entity.News;
import com.yxy.pojo.vo.NewsPageQueryVO;
import com.yxy.pojo.vo.NewsVO;
import com.yxy.service.NewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsMapper newsMapper;

    /**
     * 分页查询咨询列表
     * @param newsPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(NewsPageQueryDTO newsPageQueryDTO) {
        PageHelper.startPage(newsPageQueryDTO.getPage(), newsPageQueryDTO.getPageSize());
        Page<NewsPageQueryVO> page = newsMapper.pageQuery(newsPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增咨询
     * @param newsDTO
     */
    @Override
    public void add(NewsDTO newsDTO) {
        // 判断资讯标题是否存在
        News n = newsMapper.selectByTitle(newsDTO.getTitle());
        if(n != null){
            throw new NewsTitleAlreadyExistsException(MessageConstant.NEWS_TITLE_ALREADY_EXISTS);
        }
        News news = new News();
        BeanUtils.copyProperties(newsDTO, news);
        news.setCreateTime(LocalDateTime.now());
        news.setCreateUser(BaseContext.getCurrentId());
        newsMapper.insert(news);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void batchDelete(int[] ids) {
        newsMapper.deleteByIds(ids);
    }

    /**
     * 修改
     * @param newsDTO
     */
    @Override
    public void update(NewsDTO newsDTO) {
        News news = new News();
        BeanUtils.copyProperties(newsDTO, news);
        news.setUpdateTime(LocalDateTime.now());
        news.setUpdateUser(BaseContext.getCurrentId());
        newsMapper.update(news);
    }

    /**
     * 增加访问量
     * @param newId
     */
    @Transactional
    @Override
    public void addVisit(int newId) {
        // 查询原访问量
        News n = newsMapper.selectById(newId);
        // 更新访问量
        newsMapper.update(News.builder()
                .id(newId)
                .visitorNum(n.getVisitorNum() + 1)
                .build());
    }

    /**
     * 根据id查询
     * @param newId
     * @return
     */
    @Override
    public NewsVO getNewsById(int newId) {
        News news = newsMapper.selectById(newId);
        NewsVO newsVO = new NewsVO();
        BeanUtils.copyProperties(news, newsVO);
        return newsVO;
    }
}
